﻿@model IMS_FinanceRecv
@{
    Layout = "_LayoutMobile";
    ViewBag.Title = (Model.ID > 0 ? "修改" : "新增") + "应收款";
}
@section header {
    <style>
        .bottombutton {
            padding: 10px;
        }
    </style>
}
<van-nav-bar title="应收款"
             left-arrow
             :fixed="true"
@@click-left ="goBack">
</van-nav-bar>
<van-cell-group>
    <van-cell title="布行名" :value="model.PartnerName||'请选择'" is-link @@click="onInput" required></van-cell>
    <van-field v-model="model.DeliveryMan"
               input-algn='right'
               label="送货人"
               placeholder="请输入送货人"
               required
               clearable></van-field>
    <van-cell title="送货日期" :value="model.DeliveryDate||'请选择'" is-link @@click="showDeliveryDate = true" required></van-cell>
    <section class="van-doc-demo-block">
        <h2 class="van-doc-demo-block__title">送货单</h2>
        <van-uploader v-model="fileSHDs" :before-read="beforeSHDRead" :before-delete="beforeSHDDelete"></van-uploader>
    </section>
    <van-cell title="加工类型" :value="model.MachiningTypeText||'请选择'" is-link @@click="showMachiningType = true" required></van-cell>
    <van-field type="number" v-model="model.Rolls"
               label="卷数"
               placeholder="请输入卷数"
               required></van-field>
    <van-field type="number" v-model="model.Meters"
               label="米数"
               placeholder="请输入米数"
               required
               @@input="onMetersChange"></van-field>
    <van-field type="number" v-model="model.Price"
               label="单价"
               placeholder="请输入单价"
               required
               @@input="onPriceChange"></van-field>
    <van-cell title="总价" :value="model.Total" required></van-cell>
    <section class="van-doc-demo-block">
        <h2 class="van-doc-demo-block__title">当期账单</h2>
        <van-uploader v-model="fileDQZDs" :before-read="beforeDQZDRead" :before-delete="beforeDQZDDelete"></van-uploader>
    </section>
    <van-cell title="总欠款金额" :value="model.TotalRecvLeft"></van-cell>
    <van-field type="number" v-model="model.PreRecvTotal"
               label-width="120px"
               label="付款金额"
               placeholder="请输入付款金额"></van-field>
</van-cell-group>
<div class="bottombutton">
    <van-button type="primary" block @@click="onSave">提交</van-button>
</div>
<van-popup v-model="showPartner" position="top">
    <van-search v-model="searchValue"
                :show-action="showAction"
                placeholder="请输入搜索关键词"
                @@input="onInput"
                @@cancel="onCancel"
                @@focus="onFocus">
    </van-search>
    <van-picker show-toolbar
                :columns="partnerColumns"
                @@cancel="showPartner = false"
                @@confirm="onPartnerConfirm">
    </van-picker>
</van-popup>
<van-popup v-model="showDeliveryDate" position="bottom">
    <van-datetime-picker v-model="currentDate" type="date"
                         @@cancel="showDeliveryDate = false"
                         @@confirm="onDeliveryDateConfirm"></van-datetime-picker>
</van-popup>
<van-popup v-model="showMachiningType" position="bottom">
    <van-picker show-toolbar
                :columns="machiningTypes"
                @@cancel="showMachiningType = false"
                @@confirm="onMachiningTypeConfirm">
    </van-picker>
</van-popup>
@section footer {
    <script type="text/javascript">
            var modelJson=@(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, new Newtonsoft.Json.JsonSerializerSettings()
                  {
                      DateFormatString = "yyyy-MM-dd HH:mm:ss"
                  })))
            var modelData = $.extend(modelJson, {});
        if(modelData.Rolls==0){
            modelData.Rolls="";
        }
        if(modelData.Meters==0){
            modelData.Meters="";
        }
        if(modelData.Price==0){
            modelData.Price="";
        }
        if(modelData.PreRecvMeters==0){
            modelData.PreRecvMeters="";
        }
        if(modelData.PreRecvTotal==0){
            modelData.PreRecvTotal="";
        }
        const fileTypes = ["image/jpg", "image/jpeg", "image/png"];//文件后缀只能是这几类
        var pageApp = new Vue({
             el: '#app',
                data: {
                        active:'due',
                        model:modelData,
                        machiningTypes:@(Json.Serialize(ViewBag.MachiningTypes)),
                        showPartner:false,
                        showAction:false,
                        searchValue:'',
                        partnerColumns:[],
                        showDeliveryDate:false,
                        currentDate:new Date(),
                        showMachiningType:false,
                        fileSHDs:[],
                        fileDQZDs:[],
                },
                    methods: {
                        goBack(){
                            window.location.href = '@(Url.Action("MobileList", "FinanceRecv"))';
                        },
                        calcTotal: function (para1, para2) {
                            para1 = para1 || 0;
                            para2 = para2 || 0;
                            var result;
                            result = math.bignumber(para1).mul(math.bignumber(para2));
                            return math.format(result, { notation: 'fixed', precision: 2 });
                        },
                        onMetersChange(val){
                            modelData.Total = this.calcTotal(modelData.Meters,modelData.Price);
                        },
                        onPriceChange(val){
                            modelData.Total = this.calcTotal(modelData.Meters,modelData.Price);
                        },
                        onInput() {
                            const _this=this;
                            _this.showPartner = true;
                                    utils.ajaxPost('@(Url.Action("Autocomplete", "Partner"))', {query:_this.searchValue}, function (resp) {
                                         _this.partnerColumns= resp.suggestions.map(m=>{
                                            m.text = m.Name;
                                            return m;
                                         });
                                    }, function (msg) {
                                        console.log(msg);
                                    });
                        },
                        onFocus() {
                          this.showAction = true;
                        },
                        onCancel() {
                          this.showAction = false;
                        },
                         beforeSHDRead(file) {
                             const _this=this;
                               if (fileTypes.indexOf(file.type)<0) {
                                  vant.Toast('请上传 jpg、jpeg、png 格式图片');
                                  return false;
                                }
                                   var formData = new FormData();
                                    formData.append('file', file);
                                    formData.append('tblID', '@((int)TableCode.BJG_Machining)');
                                    formData.append('infoID', this.model.ID);
                                    fetch('@(Url.Action("Upload", "Sys_Attachment"))', {
                                        method: 'POST',
                                        body: formData,
                                    })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('网络响应错误');
                                        }
                                        return response.text(); // 或者 response.json() 如果你期望JSON响应
                                    })
                                    .then(response => {
                                            const resp= JSON.parse(response);
                                        if(resp&&resp.r)
                                        {
                                            file.ID = resp.data.ID;
                                            modelData.SHDs.push({
                                                ID:resp.data.ID,
                                                name:resp.data.title,
                                                url:resp.data.url,
                                                size:resp.data.size,
                                            });
                                        }
                                    })
                                    .catch(error => {
                                        console.error('文件上传失败', error);
                                    });
                                    return true;
                                },
                         beforeDQZDRead(file) {
                             const _this=this;
                               if (fileTypes.indexOf(file.type)<0) {
                                  vant.Toast('请上传 jpg、jpeg、png 格式图片');
                                  return false;
                                }
                                   var formData = new FormData();
                                    formData.append('file', file);
                                    formData.append('tblID', '@((int)TableCode.BJG_Bill)');
                                    formData.append('infoID', this.model.ID);
                                    fetch('@(Url.Action("Upload", "Sys_Attachment"))', {
                                        method: 'POST',
                                        body: formData,
                                    })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error('网络响应错误');
                                        }
                                        return response.text(); // 或者 response.json() 如果你期望JSON响应
                                    })
                                    .then(response => {
                                            const resp= JSON.parse(response);
                                        if(resp&&resp.r)
                                        {
                                            file.ID = resp.data.ID;
                                            modelData.DQZDs.push({
                                                ID:resp.data.ID,
                                                name:resp.data.title,
                                                url:resp.data.url,
                                                size:resp.data.size,
                                            });
                                        }
                                    })
                                    .catch(error => {
                                        console.error('文件上传失败', error);
                                    });
                                    return true;
                                },
                        beforeSHDDelete(files, detail)
                        {
                            utils.ajaxPost('@(Url.Action("Delete", "Sys_Attachment"))', {id:files.ID}, function (resp) {
                                return true;
                            }, function (msg) {
                                return false;
                            });
                                return true;
                        },
                        beforeDQZDDelete(files, detail)
                        {
                            utils.ajaxPost('@(Url.Action("Delete", "Sys_Attachment"))', {id:files.ID}, function (resp) {
                                return true;
                            }, function (msg) {
                                return false;
                            });
                                return true;
                        },
                        onPartnerConfirm(value,index) {
                            const partner = this.partnerColumns[index];
                            if(partner){
                              modelData.PartnerID = partner.ID;
                              modelData.PartnerName = partner.Name;
                              this.statistics(partner.ID);
                            }
                              this.showPartner = false;
                        },
                        statistics(partnerid){
                            utils.ajaxPost('@(Url.Action("Statistics", "FinanceRecvDue"))', { partnerid}, function (resp) {
                                    if(resp&&resp.r&&resp.data)
                                    {
                                        modelData.TotalRecvLeft = resp.data.TotalRecvLeft;
                                    }
                            }, function (msg) {
                            });
                        },
                        onDeliveryDateConfirm(value) {
                              modelData.DeliveryDate = this.$options.filters.formatDate(value);
                              this.showDeliveryDate = false;
                        },
                        onMachiningTypeConfirm(value,index) {
                            const mType = this.machiningTypes[index];
                            if(mType){
                              modelData.MachiningType = mType.value;
                              modelData.MachiningTypeText = mType.text;
                            }
                            this.showMachiningType = false;
                        },
                        onSave(){
                            const data = this.model;
                            if(!data.PartnerID||data.PartnerID==0)
                            {
                                vant.Toast('请选择客户');
                                return;
                            }
                            if(!data.MachiningType||data.MachiningType==0)
                            {
                                vant.Toast('请选择加工类型');
                                return;
                            }
                            if(!data.DeliveryMan||data.DeliveryMan.length<=0)
                            {
                                vant.Toast('请输入送货人');
                                return;
                            }
                            if(!data.Rolls)
                            {
                                vant.Toast('请输入卷数');
                                return;
                            }
                            if(!data.Meters)
                            {
                                vant.Toast('请输入米数');
                                return;
                            }
                            if(!data.Price)
                            {
                                vant.Toast('请输入单价');
                                return;
                            }
                            if(!data.PreRecvTotal)
                            {
                                data.PreRecvTotal=0;
                            }
                            if(data.PreRecvTotal>data.Total)
                            {
                                vant.Toast('付款金额不能大于本次加工总价');
                                return;
                            }
                            utils.ajaxPost('@(Url.Action("Save", "FinanceRecv"))', data, function (resp) {
                                console.log(resp.data);
       
                                location.href = '@(Url.Action("MobileViewDetail", "FinanceRecv", new { id = "" }))/'+resp.data+'?nc=' + new Date().getTime();
                            }, function (msg) {
                                console.log(msg);
                            });
                        }
                },
            filters: {
                formatDate: function (val) {
                    return utils.formatDate(val, 'yyyy-MM-dd');
                },
            },
        });
        $(function () {
            if(!isMobile())
            {
                    window.location.href = '@(Url.Action("Edit", "FinanceRecv"))/' + modelData.ID + '?nc=' + new Date().getTime();
            }
        });

        function isMobile() {
          const regExp = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
          return regExp.test(navigator.userAgent);
        }
    </script>
}